# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql

class ZhihuPipeline(object):
    def process_item(self, item, spider):
        try:
            conn=pymysql.connect(host="127.0.0.1", user="root", password="root", db="zhihu", charset="utf8")
            for i in range(0,len(item["topicName"])):
                topicName=item["topicName"][i]
                topicID=item["topicID"][i]
                sql1="insert into topic(name,topicid) values('"+topicName+"','"+topicID+"')"
                conn.query(sql1)
                conn.commit()
            for i in range(0,len(item["sub_id"])):
                subid=item["sub_id"][i]
                subtopic=item["sub_topic"][i]
                sql2 = "insert into subtopic(subid,subname) values('" + subid + "','" + subtopic + "')"
                conn.query(sql2)
                conn.commit()
            for i in range(0,len(item["articleAuthor"])):
                articleAuthor=item["articleAuthor"][i]
                articleTitle=item["articleTitle"][i]
                sql3 = "insert into article(articleTitle,articleAuthor) values('" + articleTitle + "','" + articleAuthor + "')"
                conn.query(sql3)
                conn.commit()
            for i in range(0,1):
                questionTitle=item["questionTitle"][i]
                questionDetail=item["questionDetail"][i]
                sql4 = "insert into questions(questionTitle,questionDetails) values('" + questionTitle + "','" + questionDetail + "')"
                conn.query(sql4)
                conn.commit()
            for i in range(0,1):
                answerAuthor=item["answerAuthor"][i]
                answerContent=item["answerContent"][i]
                sql5 = "insert into answers(answerAuthor,answerContent) values('" + answerAuthor + "','" + answerContent + "')"
                conn.query(sql5)
                conn.commit()
            conn.close()
        except Exception as err:
            print(err)
        return item
